package com.tchy.cloud.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.tchy.cloud.entity.CPlatformEntity;
import com.tchy.cloud.entity.CQDimEntity;
import com.tchy.cloud.entity.CQuestionnaireSortEntity;
import org.apache.log4j.Logger;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Property;
import org.hibernate.criterion.Restrictions;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.ComboTree;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.common.model.json.TreeGrid;
import org.jeecgframework.core.common.service.CommonService;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil;
import org.jeecgframework.core.util.MutiLangUtil;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.core.util.oConvertUtils;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.tag.vo.datatable.SortDirection;
import org.jeecgframework.tag.vo.easyui.ComboTreeModel;
import org.jeecgframework.tag.vo.easyui.TreeGridModel;
import org.jeecgframework.web.system.pojo.base.TSDepart;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.jeecgframework.web.system.pojo.base.TSUserOrg;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.web.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 量表分类
 * xmweilove
 */
@Controller
@RequestMapping("/questSortController")
public class CQuestionnaireSortController extends BaseController {
    private static final Logger logger = Logger.getLogger(CQuestionnaireSortController.class);

    @Autowired
    private CommonService commonService;

    /**
     * 量表分类树形展示页面跳转
     *
     * @return
     */
    @RequestMapping(params = "index")
    public ModelAndView index() {
        return new ModelAndView("clound/questSort/index");
    }

    /**
     * 量表分类，树形展示数据
     *
     * @param request
     * @param response
     * @param treegrid
     * @return
     */
    @RequestMapping(params = "datatreegrid")
    @ResponseBody
    public Object datatreegrid(CQuestionnaireSortEntity questionnaireSortEntity, HttpServletRequest request, HttpServletResponse response, TreeGrid treegrid) {
        CriteriaQuery cq = new CriteriaQuery(CQuestionnaireSortEntity.class);
        if ("yes".equals(request.getParameter("isSearch"))) {
            treegrid.setId(null);
            questionnaireSortEntity.setQsId(null);
        }
        if (null != questionnaireSortEntity.getName()) {
            org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, questionnaireSortEntity);
        }
        if (treegrid.getId() != null) {
            cq.eq("parentQS.qsId", Integer.valueOf(treegrid.getId()));
        }
        if (treegrid.getId() == null) {
            cq.isNull("parentQS");
        }
        cq.addOrder("sort", SortDirection.asc);
        cq.add();
        List<TreeGrid> qsList = commonService.getListByCriteriaQuery(cq, false);
        if (qsList.size() == 0 && questionnaireSortEntity.getName() != null) {
            cq = new CriteriaQuery(CQuestionnaireSortEntity.class);
            CQuestionnaireSortEntity parentQS = new CQuestionnaireSortEntity();
            questionnaireSortEntity.setParentQS(parentQS);
            org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, parentQS);
            qsList = commonService.getListByCriteriaQuery(cq, false);
        }
        List<TreeGrid> treeGrids = new ArrayList<TreeGrid>();
        TreeGridModel treeGridModel = new TreeGridModel();
        treeGridModel.setTextField("name");//显示的名称
        treeGridModel.setParentText("parentQS_name");//显示的父类名称
        treeGridModel.setParentId("parentQS_qsId");//显示的父类id
        treeGridModel.setSrc("qDesc");//本级别描述
        treeGridModel.setIdField("qsId");//显示数据的id
        treeGridModel.setChildList("childresQS");

        treeGridModel.setCode("orgType");

        treeGridModel.setFunctionBelong("orgType"); //类型
//        Map<String, Object> fieldMap = new HashMap<String, Object>();
//        fieldMap.put("orgCode", "orgCode");
        //fieldMap.put("orgType", "orgType");
//        treeGridModel.setFieldMap(fieldMap);
        treeGrids = commonService.treegrid(qsList, treeGridModel);

        JSONArray jsonArray = new JSONArray();
        for (TreeGrid treeGrid : treeGrids) {

            treeGrid.setCode(treeGrid.getFunctionBelong());

            jsonArray.add(JSON.parse(treeGrid.toJson()));
        }
        return jsonArray;
    }

    /**
     * 分类新增或修改页面跳转
     *
     * @param questionnaireSortEntity
     * @param req
     * @return
     */
    @RequestMapping(params = "addorupdate")
    public ModelAndView addorupdate(CQuestionnaireSortEntity questionnaireSortEntity, HttpServletRequest req) {
        CQuestionnaireSortEntity entity = new CQuestionnaireSortEntity();
        if (questionnaireSortEntity.getQsId() != null) {
            CQuestionnaireSortEntity sortEntity = commonService.getEntity(questionnaireSortEntity.getClass(), questionnaireSortEntity.getQsId());
            req.setAttribute("entity", sortEntity);
        }
        return new ModelAndView("clound/questSort/addorupdate");
    }

    @RequestMapping(params = "del")
    @ResponseBody
    public AjaxJson del(CQuestionnaireSortEntity entity, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        Integer sid = entity.getQsId();
        String sql = "select * from c_questionnaire where questionnaire_sort_id = ?";
        List<Map<String, Object>> list = commonService.findForJdbc(sql, new Object[]{sid});
        if (list.size() > 0) {
            j.setMsg("该类型下存在量表，不允许删除。");
        } else {
            try {
                CQuestionnaireSortEntity obj = commonService.getEntity(CQuestionnaireSortEntity.class, entity.getQsId());
                commonService.delete(obj);
                j.setMsg("删除成功");
            } catch (Exception e) {
                j.setMsg("删除失败。");
            }

        }


        return j;
    }
    // update-end--Author:zhangguoming  Date:20140825 for：添加业务逻辑；添加类注释；
//
//	public void upEntity(TSDepart depart) {
//		List<TSUser> users = systemService.findByProperty(TSUser.class, "TSDepart.id", depart.getId());
//		if (users.size() > 0) {
//			for (TSUser tsUser : users) {
//				//tsUser.setTSDepart(null);
//				//systemService.saveOrUpdate(tsUser);
//				systemService.delete(tsUser);
//			}
//		}
//	}


    /**
     * 添加部门
     *
     * @param entity
     * @return
     */
    @RequestMapping(params = "save")
    @ResponseBody
    public AjaxJson save(CQuestionnaireSortEntity entity, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        String pid = request.getParameter("parentQS.qsId");
        String qlevel = "";
        CQuestionnaireSortEntity sortParent = null;
        if (pid.equals("")) {//无上级
            entity.setParentQS(null);
        } else {//有上级的时候获取上级对象
            sortParent = commonService.getEntity(CQuestionnaireSortEntity.class, Integer.valueOf(pid));
            entity.setParentQS(sortParent);
        }
        try {
            if (entity.getQsId() != null) {
                CQuestionnaireSortEntity sortEntity = commonService.getEntity(CQuestionnaireSortEntity.class, entity.getQsId());
                MyBeanUtils.copyBeanNotNull2Bean(entity, sortEntity);
                commonService.saveOrUpdate(sortEntity);
            } else {
                commonService.save(entity);
            }

            if (pid.equals("")) {//无上级
                qlevel = "," + entity.getQsId() + ",";
            } else {
                qlevel = sortParent.getQlevel() + entity.getQsId() + ",";
            }
            entity.setQlevel(qlevel);
            commonService.saveOrUpdate(entity);
            j.setMsg("操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e);
            j.setMsg("操作失败");
        }
        return j;
    }

//	/**
//	 * 部门列表页面跳转
//	 *
//	 * @return
//	 */
//	@RequestMapping(params = "update")
//	public ModelAndView update(TSDepart depart, HttpServletRequest req) {
//		List<TSDepart> departList = systemService.getList(TSDepart.class);
//		req.setAttribute("departList", departList);
//		if (StringUtil.isNotEmpty(depart.getId())) {
//			depart = systemService.getEntity(TSDepart.class, depart.getId());
//			req.setAttribute("depart", depart);
//		}
//		return new ModelAndView("system/depart/depart");
//	}
//

    /**
     * 父级权限列表
     *
     * @param request
     * @param comboTree
     * @return
     */
    @RequestMapping(params = "setPFunction")
    @ResponseBody
    public List<ComboTree> setPFunction(HttpServletRequest request, ComboTree comboTree) {
        CriteriaQuery cq = new CriteriaQuery(CQuestionnaireSortEntity.class);
//        if(null != request.getParameter("selfId")){
//            cq.notEq("id", request.getParameter("selfId"));
//        }
        if (comboTree.getId() != null) {
            cq.eq("parentQS.qsId", comboTree.getId());
        }
        if (comboTree.getId() == null) {
            cq.isNull("parentQS");
        }
        cq.add();
        List<TSDepart> departsList = commonService.getListByCriteriaQuery(cq, false);
        List<ComboTree> comboTrees = new ArrayList<ComboTree>();
        ComboTreeModel comboTreeModel = new ComboTreeModel("qsId", "name", "childresQS");
        comboTrees = commonService.ComboTree(departsList, comboTreeModel, null, true);
        return comboTrees;

    }
//	/**
//	 * 部门列表，树形展示
//	 * @param request
//	 * @param response
//	 * @param treegrid
//	 * @return
//	 */
//	@RequestMapping(params = "departgrid")
//	@ResponseBody
//	public Object departgrid(TSDepart tSDepart,HttpServletRequest request, HttpServletResponse response, TreeGrid treegrid) {
//		CriteriaQuery cq = new CriteriaQuery(TSDepart.class);
//		if("yes".equals(request.getParameter("isSearch"))){
//			treegrid.setId(null);
//			tSDepart.setId(null);
//		}
//		if(null != tSDepart.getDepartname()){
//			org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, tSDepart);
//		}
//		if (treegrid.getId() != null) {
//			cq.eq("TSPDepart.id", treegrid.getId());
//		}
//		if (treegrid.getId() == null) {
//			cq.isNull("TSPDepart");
//		}
//		cq.add();
//		List<TreeGrid> departList =null;
//		departList=systemService.getListByCriteriaQuery(cq, false);
//		if(departList.size()==0&&tSDepart.getDepartname()!=null){
//			cq = new CriteriaQuery(TSDepart.class);
//			TSDepart parDepart = new TSDepart();
//			tSDepart.setTSPDepart(parDepart);
//			org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, tSDepart);
//		    departList =systemService.getListByCriteriaQuery(cq, false);
//		}
//		List<TreeGrid> treeGrids = new ArrayList<TreeGrid>();
//		TreeGridModel treeGridModel = new TreeGridModel();
//		treeGridModel.setTextField("departname");
//		treeGridModel.setParentText("TSPDepart_departname");
//		treeGridModel.setParentId("TSPDepart_id");
//		treeGridModel.setSrc("description");
//		treeGridModel.setIdField("id");
//		treeGridModel.setChildList("TSDeparts");
//
//		treeGridModel.setCode("orgType");
//
//		treeGridModel.setFunctionBelong("orgType"); //类型
//        Map<String,Object> fieldMap = new HashMap<String, Object>();
//        fieldMap.put("orgCode", "orgCode");
//        //fieldMap.put("orgType", "orgType");
//        treeGridModel.setFieldMap(fieldMap);
//        treeGrids = systemService.treegrid(departList, treeGridModel);
//
//        JSONArray jsonArray = new JSONArray();
//        for (TreeGrid treeGrid : treeGrids) {
//
//			treeGrid.setCode(treeGrid.getFunctionBelong());
//
//            jsonArray.add(JSON.parse(treeGrid.toJson()));
//        }
//        return jsonArray;
//	}
//	//----
//	/**
//	 * 方法描述:  查看成员列表
//	 * 作    者： yiming.zhang
//	 * 日    期： Dec 4, 2013-8:53:39 PM
//	 * @param request
//	 * @param departid
//	 * @return
//	 * 返回类型： ModelAndView
//	 */
//	@RequestMapping(params = "userList")
//	public ModelAndView userList(HttpServletRequest request, String departid) {
//		request.setAttribute("departid", departid);
//		return new ModelAndView("system/depart/departUserList");
//	}
//
//	/**
//	 * 方法描述:  成员列表dataGrid
//	 * 作    者： yiming.zhang
//	 * 日    期： Dec 4, 2013-10:40:17 PM
//	 * @param user
//	 * @param request
//	 * @param response
//	 * @param dataGrid
//	 * 返回类型： void
//	 */
//	@RequestMapping(params = "userDatagrid")
//	public void userDatagrid(TSUser user,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
//		CriteriaQuery cq = new CriteriaQuery(TSUser.class, dataGrid);
//		//查询条件组装器
//		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, user);
//		String departid = oConvertUtils.getString(request.getParameter("departid"));
//		if (!StringUtil.isEmpty(departid)) {
////            update-start--Author:zhangguoming  Date:20140825 for：用户表字段变更后的查询字段修改
//			DetachedCriteria dc = cq.getDetachedCriteria();
//			DetachedCriteria dcDepart = dc.createCriteria("userOrgList");
//			dcDepart.add(Restrictions.eq("tsDepart.id", departid));
//            // 这种方式也是可以的
////            DetachedCriteria dcDepart = dc.createAlias("userOrgList", "userOrg");
////            dcDepart.add(Restrictions.eq("userOrg.tsDepart.id", departid));
////            update-end--Author:zhangguoming  Date:20140825 for：用户表字段变更后的查询字段修改
//		}
//		Short[] userstate = new Short[] { Globals.User_Normal, Globals.User_ADMIN };
//		cq.in("status", userstate);
//		cq.add();
//		this.systemService.getDataGridReturn(cq, true);
//		TagUtil.datagrid(response, dataGrid);
//	}
//	//----
//
////    update-start--Author:zhangguoming  Date:20140826 for：获取机构树；
//    /**
//     * 获取机构树-combotree
//     * @param request
//     * @return
//     */
//    @RequestMapping(params = "getOrgTree")
//    @ResponseBody
//    public List<ComboTree> getOrgTree(HttpServletRequest request) {
////        findHql不能处理is null条件
////        List<TSDepart> departsList = systemService.findHql("from TSPDepart where TSPDepart.id is null");
//        List<TSDepart> departsList = systemService.findByQueryString("from TSDepart where TSPDepart.id is null");
//        List<ComboTree> comboTrees = new ArrayList<ComboTree>();
//        ComboTreeModel comboTreeModel = new ComboTreeModel("id", "departname", "TSDeparts");
//        comboTrees = systemService.ComboTree(departsList, comboTreeModel, null, true);
//        return comboTrees;
//    }
////    update-end--Author:zhangguoming  Date:20140826 for：获取机构树；
//
//
////    update-start--Author:zhangguoming  Date:20140826 for：添加已有用户到组织机构；
//    /**
//     * 添加 用户到组织机构 的页面  跳转
//     * @param req request
//     * @return 处理结果信息
//     */
//    @RequestMapping(params = "goAddUserToOrg")
//    public ModelAndView goAddUserToOrg(HttpServletRequest req) {
//        req.setAttribute("orgId", req.getParameter("orgId"));
//        return new ModelAndView("system/depart/noCurDepartUserList");
//    }
//    /**
//     * 获取 除当前 组织之外的用户信息列表
//     * @param request request
//     * @return 处理结果信息
//     */
//    @RequestMapping(params = "addUserToOrgList")
//    public void addUserToOrgList(TSUser user, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
//        String orgId = request.getParameter("orgId");
//
//        CriteriaQuery cq = new CriteriaQuery(TSUser.class, dataGrid);
//        org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, user);
//
//        // 获取 当前组织机构的用户信息
//        CriteriaQuery subCq = new CriteriaQuery(TSUserOrg.class);
//        subCq.setProjection(Property.forName("tsUser.id"));
//        subCq.eq("tsDepart.id", orgId);
//        subCq.add();
//
//        cq.add(Property.forName("id").notIn(subCq.getDetachedCriteria()));
//        cq.add();
//
//        this.systemService.getDataGridReturn(cq, true);
//        TagUtil.datagrid(response, dataGrid);
//    }
//    /**
//     * 添加 用户到组织机构
//     * @param req request
//     * @return 处理结果信息
//     */
//    @RequestMapping(params = "doAddUserToOrg")
//    @ResponseBody
//    public AjaxJson doAddUserToOrg(HttpServletRequest req) {
//        AjaxJson j = new AjaxJson();
//        TSDepart depart = systemService.getEntity(TSDepart.class, req.getParameter("orgId"));
//        saveOrgUserList(req, depart);
//        message =  MutiLangUtil.paramAddSuccess("common.user");
////      systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
//        j.setMsg(message);
//
//        return j;
//    }
//    /**
//     * 保存 组织机构-用户 关系信息
//     * @param request request
//     * @param depart depart
//     */
//    private void saveOrgUserList(HttpServletRequest request, TSDepart depart) {
//        String orgIds = oConvertUtils.getString(request.getParameter("userIds"));
//
//        List<TSUserOrg> userOrgList = new ArrayList<TSUserOrg>();
//        List<String> userIdList = extractIdListByComma(orgIds);
//        for (String userId : userIdList) {
//            TSUser user = new TSUser();
//            user.setId(userId);
//
//            TSUserOrg userOrg = new TSUserOrg();
//            userOrg.setTsUser(user);
//            userOrg.setTsDepart(depart);
//
//            userOrgList.add(userOrg);
//        }
//        if (!userOrgList.isEmpty()) {
//            systemService.batchSave(userOrgList);
//        }
//    }
////    update-end--Author:zhangguoming  Date:20140826 for：添加已有用户到组织机构
//
////    update-start--Author:zhangguoming  Date:20140827 for：用户列表页面 组织机构查询条件：选择组织机构列表 相关操作
//    /**
//     * 用户选择机构列表跳转页面
//     *
//     * @return
//     */
//    @RequestMapping(params = "departSelect")
//    public String departSelect() {
//        return "system/depart/departSelect";
//    }
//    /**
//     * 角色显示列表
//     *
//     * @param response response
//     * @param dataGrid dataGrid
//     */
//    @RequestMapping(params = "departSelectDataGrid")
//    public void datagridRole(HttpServletResponse response, DataGrid dataGrid) {
//        CriteriaQuery cq = new CriteriaQuery(TSDepart.class, dataGrid);
//        this.systemService.getDataGridReturn(cq, true);
//        TagUtil.datagrid(response, dataGrid);
//    }
////    update-end--Author:zhangguoming  Date:20140827 for：用户列表页面 组织机构查询条件：选择组织机构列表 相关操作
}
